package heart;

import bese.NettyMessage;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.ScheduledFuture;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * Created by wuhui on 2016/8/4.
 */
@Slf4j
public class HeartBeatReqHandler extends ChannelHandlerAdapter {
    private volatile ScheduledFuture<?> heartBeat;
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessage nettyMessage = (NettyMessage) msg;
        //握手成功，主动发送心跳消息
        if(nettyMessage.getHeader()!=null&&nettyMessage.getHeader().getType()==2){
            heartBeat =ctx.executor().scheduleAtFixedRate(new HeartBeatReqHandler.HeartBeatTask(ctx),0,5, TimeUnit.SECONDS);
        }else {
           ctx.fireChannelRead(msg);
        }
    }
    private class HeartBeatTask implements  Runnable{
        private final ChannelHandlerContext ctx;
        NettyMessage heart  = buildHeatBeat();
        private HeartBeatTask( ChannelHandlerContext ctx) {
           this.ctx  = ctx;
        }
        @Override
        public void run() {
            ctx.writeAndFlush(heart);
        }
        private NettyMessage buildHeatBeat(){
            return  NettyMessage.newNettyMessage((byte)2);
        }
    }
}
